<?php
namespace app\admin\controller;
use think\Db;

class Delivery extends Common {
	
	public function index(){
		// 唐峰康改  
		$lists = db('user')->where(array('check_status' => 1))->paginate(config('PAGE_SIZE'));

		$temp_list = array();
		foreach ($lists as $k => $v) {
			$userId = $v['id'];
			$deliverMoney = db('delivery_order')->where("status =2 and userId = '{$userId}'")->sum('deliverMoney');
			$temp_list[$k]=$v;
			if ($deliverMoney) {
				$temp_list[$k]['settlement_money'] = $deliverMoney;
			}else{
				$temp_list[$k]['settlement_money'] = 0.00;
			}

		}
		// $lists = db('user')->where(array('check_status' => 1,'mobilecheck' => 1))->paginate(config('PAGE_SIZE'));
		$this->assign('page',$lists->render());
		$lists = $temp_list;
		$this->assign('lists',$lists);
		return $this->fetch();
	}
	
	public function verifyuser(){
		$lists = db('user')->where(array('check_status' => 0))->paginate(config('PAGE_SIZE'));
		$temp_list = array();
		foreach ($lists as $k => $v) {
			$userId = $v['id'];
			$deliverMoney = db('delivery_order')->where("status =2 and userId = '{$userId}'")->sum('deliverMoney');
			$temp_list[$k]=$v;
			if ($deliverMoney) {
				$temp_list[$k]['settlement_money'] = $deliverMoney;
			}else{
				$temp_list[$k]['settlement_money'] = 0.00;
			}

		}
		$this->assign('page',$lists->render());
		$lists = $temp_list;
		$this->assign('lists',$lists);
		return $this->fetch('index');
	}
	
	public function deleteuser(){
		if (!request()->isAjax()) $this->error('操作失败');
		$id = input('id');
		if (db('user')->where(array('id' => $id))->delete()){
			$this->ajaxReturn(array('code' => 1,'reload' => 1,'msg' => '删除成功'));
		}else{
			$this->ajaxReturn(array('code' => 0,'msg' => '删除失败'));
		}
	}
	
	public function add_user(){
		$province = db('region')->where(array('pid' => 1))->select();
		$this->assign('province',$province);
		return $this->fetch();
	}
	
	public function add_user_handler(){
		$data = $this->check_user_post();
		$upload_data = $this->user_upload();
		$data = array_merge($data,$upload_data);
		$data['time'] = time();
		$user = db('user');
		if ($data['user_face'] == '') {
			$this->error('请上传头像!');
			return;
		}
		if ($data['user_face'] == '' || $data['card_thumb'] == ''|| $data['card_thumb2'] == '' || $data['card_thumb3'] == '') {
			$this->error('请上传身份证相关照片!');
			return;
		}
		if ($user->where(array('username' => $data['username']))->find()) $this->ajaxReturn(array('code' => 0,'msg' => '用户名已存在'));
		if ($user->where(array('mobile' => $data['mobile']))->find()) $this->ajaxReturn(array('code' => 0,'msg' => '手机号码已存在'));
		$data['passsalt'] = create_salt();
		$data['pay_passsalt'] = create_salt();
		$data['password'] = optimizedSaltPwd($data['password'], $data['passsalt']);
		$data['det_password'] = optimizedSaltPwd($data['det_password'], $data['pay_passsalt']);
		if($user->insert($data)){
			if (!empty($data['delivery_id'])){
				$uid = $user->getLastInsID();
				$user_section = db('user_section');
				$sectionData = array();
				$arr = explode(',', $data['delivery_id']);
				foreach ($arr as $key => $value){
					$sectionData[] = array(
						'uid' => $uid,
						'section_id' => $value,
					);
				}
				$user_section->insertAll($sectionData);
			}
			$this->ajaxReturn(array('code' => 1,'reload' => 1,'url' => url('index'),'msg' => '新增成功'));
		} else{
			$this->error('新增失败');
		}
	}
	
	private function user_upload(){
		$user_face = '';
		$thumb = '';
		$thumb2 = '';
		$thumb3 = '';
		$userFace = request()->file('user_face');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if ($userFace){
			$info = $userFace->move(ROOT_PATH . DS . config('uplaod') .DS.'face');
			if ($info){
				$user_face = config('uplaod').'/face/'.str_replace('\\', '/', $info->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		
		$cardThumb = request()->file('card_thumb');
		if ($cardThumb){
			// 移动到框架应用根目录/public/uploads/ 目录下
			$card_thumb_file = $cardThumb->move(ROOT_PATH . DS . config('uplaod') .DS.'idcard');
			if ($card_thumb_file){
				$thumb = config('uplaod').'/idcard/'.str_replace('\\', '/', $card_thumb_file->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$cardThumb2 = request()->file('card_thumb2');
		if ($cardThumb2){
			// 移动到框架应用根目录/public/uploads/ 目录下
			$card_thumb_file2 = $cardThumb2->move(ROOT_PATH . DS . config('uplaod') .DS.'idcard');
			if ($card_thumb_file2){
				$thumb2 = config('uplaod').'/idcard/'.str_replace('\\', '/', $card_thumb_file2->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$cardThumb3 = request()->file('card_thumb3');
		if ($cardThumb3){
			// 移动到框架应用根目录/public/uploads/ 目录下
			$card_thumb_file3 = $cardThumb3->move(ROOT_PATH . DS . config('uplaod') .DS.'idcard');
			if ($card_thumb_file3){
				$thumb3 = config('uplaod').'/idcard/'.str_replace('\\', '/', $card_thumb_file3->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$data['user_face'] = $user_face;
		$data['card_thumb'] = $thumb;
		$data['card_thumb2'] = $thumb2;
		$data['card_thumb3'] = $thumb3;
		return $data;
	}
	
	private function check_user_post(){
		if (!request()->isAjax()) $this->error('操作失败');
		$address = input('post.address/a');
		$address = implode(',', $address);
		$data = array(
			'username' => input('post.username'),
			'password' => input('post.password'),
			'truename' => input('post.truename'),
			'det_password' => input('post.det_password'),
			'mobile' => input('post.mobile'),
			'id_card' => input('post.id_card'),
			'province' => input('post.province'),
			'city' => input('post.city'),
			'area' => input('post.area'),
			'delivery_id' => $address,
			'status' => input('post.status')
		);
		if (empty($data['username'])) $this->ajaxReturn(array('code' => 0,'msg' => '用户名不能为空'));
		$id = intval(input('post.id'));
		if (!$id || !empty($data['password'])){
			if (!(mb_strlen($data['password'],'utf-8') >= 6 && mb_strlen($data['password']) <= 20)) $this->ajaxReturn(array('code' => 0,'msg' => '密码长度6到20位'));
		}
		if (!$id || !empty($data['det_password'])){
			if (!(mb_strlen($data['det_password'],'utf-8') >= 6 && mb_strlen($data['password']) <= 20)) $this->ajaxReturn(array('code' => 0,'msg' => '密码长度6到20位'));
		}
		if (empty($data['truename'])) $this->ajaxReturn(array('code' => 0,'msg' => '真实姓名不能为空'));
		if (empty($data['mobile'])) $this->ajaxReturn(array('code' => 0,'msg' => '手机号码不能为空'));
		if (!_checkmobile($data['mobile'])) $this->ajaxReturn(array('code' => 0,'msg' => '手机号码格式不正确'));
		if (!isCreditNo($data['id_card'])) $this->ajaxReturn(array('code' => 0,'msg' => '身份证号码不正确'));
		return $data;
	}
	
	public function edit_user(){
		$id = intval(input('id'));
		if (!$id) $this->error('操作失败');
		$data = db('user')->where(array('id' => $id))->find();
		if (empty($data)) $this->error('数据不存在');
		$province = db('region')->where(array('pid' => 1))->select();
		$city = db('region')->where(array('pid' => $data['province']))->select();
		$area = db('region')->where(array('pid' => $data['city']))->select();
	

		$this->assign('province',$province);
		$this->assign('city',$city);
		$this->assign('area',$area);
		$html = '';
		// foreach ($address_section as $key => $value){
		// 	$html .= '<label><input name="address[]" type="checkbox" checked="checked" value="'.$value['id'].'" class="ace">';
		// 	$html .= '<span class="lbl"> '.$value['section'].'</span></label>';
		// }
		// 必须先判断配送区域是否存在 app注册的不存在
		if ($data['delivery_id']) {
			$address_section = db('address_section')->where(array('id' => array('IN',$data['delivery_id'])))->select();
			// 唐峰康改  应该是获取全部地区的社区，是自己的配送范围则选中
			$cityId = $address_section[0]['city'];
			$city_address_info =  db('address_section')->where(array('city' => $cityId))->select();
			$user_address_ids = explode(',',$data['delivery_id']);
			
			$ids_num = count($user_address_ids) - 1;
			foreach ($city_address_info as $k => $v) {
				foreach ($user_address_ids as $kk => $id) {
					if ($v['id'] == $id) {
						$html .= '<label><input name="address[]" type="checkbox" checked="checked" value="'.$v['id'].'" class="ace">';
						$html .= '<span class="lbl"> '.$v['section'].'</span></label>';
						break;
					}elseif ($v['id'] != $id && $kk == $ids_num) {
						$html .= '<label><input name="address[]" type="checkbox" value="'.$v['id'].'" class="ace">';
						$html .= '<span class="lbl"> '.$v['section'].'</span></label>';
					}
				}
			}
		}
	

		$this->assign('checkbox_html',$html);
		$this->assign('data',$data);
		return $this->fetch();
	}
	
	public function edit_user_handler(){
		$data = $this->check_user_post();
		$upload_data = $this->user_upload();
		$data['user_face'] = empty($upload_data['user_face']) ? input('org_user_face') : $upload_data['user_face'];
		$data['card_thumb'] = empty($upload_data['card_thumb']) ? input('org_card_thumb') : $upload_data['card_thumb'];
		$data['card_thumb2'] = empty($upload_data['card_thumb2']) ? input('org_card_thumb2') : $upload_data['card_thumb2'];
		$data['card_thumb3'] = empty($upload_data['card_thumb3']) ? input('org_card_thumb3') : $upload_data['card_thumb3'];
		$id = intval(input('post.id'));
		$data['id'] = $id;
		$model = db('user');
		if ($model->where(array('id' => array('NEQ',$data['id']),'username' => $data['username']))->find()) $this->ajaxReturn(array('code' => 0,'msg' => '用户名已存在'));
		if ($model->where(array('id' => array('NEQ',$data['id']),'mobile' => $data['mobile']))->find()) $this->ajaxReturn(array('code' => 0,'msg' => '手机号码已存在'));
		if (!empty($data['password'])){
			$data['passsalt'] = create_salt();
			$data['password'] = optimizedSaltPwd($data['password'], $data['passsalt']);
		}else{
			unset($data['password']);
		}
		if (!empty($data['det_password'])){
			$data['pay_passsalt'] = create_salt();
			$data['det_password'] = optimizedSaltPwd($data['det_password'], $data['pay_passsalt']);
		}else{
			unset($data['det_password']);
		}
		if($model->update($data)){
			$user_section = db('user_section');
			$user_section->where(array('uid' => $data['id']))->delete();
			if (!empty($data['delivery_id'])){
				$sectionData = array();
				$arr = explode(',', $data['delivery_id']);
				foreach ($arr as $key => $value){
					$sectionData[] = array(
						'uid' => $data['id'],
						'section_id' => $value,
					);
				}
				$user_section->insertAll($sectionData);
			}
			$this->ajaxReturn(array('code' => 1,'reload' => 1,'url' => url('index'),'msg' => '编辑成功'));
		} else{
			$this->error('编辑失败');
		}
	}
	
	public function user_status(){
		if (!request()->isAjax()) $this->error('操作失败');
		$id = intval(input('id'));
		$data = db('user')->where(array('id' => $id))->find();
		if (!$data) $this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		$status = $data['status'] ? 0 : 1;
		$affected_row = db('user')->where(array('id' => $data['id']))->setField('status',$status);
		if (!$affected_row) $this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		if ($status){
			$this->ajaxReturn(array('classText' => 'btn-success','status' => $status,'code' => 1,'msg' => '开启'));
		}else{
			$this->ajaxReturn(array('classText' => 'btn-warning','status' => $status,'code' => 1,'msg' => '禁用'));
		}
	}
	
	public function check_status(){
		if (!request()->isAjax()) $this->error('操作失败');
		$id = intval(input('id'));
		$data = db('user')->where(array('id' => $id))->find();
		if (!$data) $this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		$status = $data['check_status'] ? 0 : 1;
		$affected_row = db('user')->where(array('id' => $data['id']))->setField('check_status',$status);
		if (!$affected_row) $this->ajaxReturn(array('code' => 0,'msg' => '操作失败'));
		if ($status){
			$this->ajaxReturn(array('classText' => 'btn-success','status' => $status,'code' => 1,'msg' => '通过'));
		}else{
			$this->ajaxReturn(array('classText' => 'btn-warning','status' => $status,'code' => 1,'msg' => '未通过'));
		}
	}
	
	public function get_area(){
		if (!request()->isAjax()) $this->error('操作失败');
		$city_id = intval(input('city_id'));
		$data = db('address_section')->where(array('city' => $city_id,'status' => 1))->select();
		$html = '';
		foreach ($data as $key => $value){
			$html .= '<label><input name="address[]" type="checkbox" value="'.$value['id'].'" class="ace">';
			$html .= '<span class="lbl"> '.$value['section'].'</span></label>';
		}
		$this->ajaxReturn($html);
	}
	
	//配送员统计
	public function counts(){
		$totalRows = db('user')->where(array('check_status' => 1))->count();
		$delivery_order = db('delivery_order');
		$where = 'status=3';
		$where2 = 'iscancel=1';
		if (isset($_POST['start']) && isset($_POST['end'])){
			$startTime = strtotime($_POST['start']);
			$endTime = strtotime($_POST['end']);
			$where .= " and time >= {$startTime} and time <= {$endTime}";
			$where2 .= " and time >= {$startTime} and time <= {$endTime}";
		}
		$finishOrderUser = $delivery_order->where($where)->field('userId')->group('userId')->select();
		$finishOrder = $delivery_order->where($where)->count('id');
		$retreatOrder = $delivery_order->where($where2)->count('id');
		$this->assign('finishOrderUser',count($finishOrderUser));
		$this->assign('finishOrder',$finishOrder);
		$this->assign('retreatOrder',$retreatOrder);
		$this->assign('totalUser',$totalRows);
		if (isset($_POST['export'])){
			$datas[] = array(
				'user_num' => $totalRows,
				'finishOrderUser' => count($finishOrderUser),
				'finishOrder' => $finishOrder,
				'retreatOrder' => $retreatOrder
			);
			$this->put_csv($datas, array('配送员数','有配送完成订单的配送人数','配送完成总订单数','退单数'), '配送员统计');
			exit;
		}
		$this->assign('lists',array());
		$this->assign('startTime',isset($_POST['start']) ? $_POST['start'] : '');
		$this->assign('endTime',isset($_POST['end']) ? $_POST['end'] : '');
		return $this->fetch();
	}
	
	public function detail(){
		$year = date('Y');
		$yearAll = array();
		$total = array();
		$totalData = array();
		$startMonth = $endMonth = $startYear = $endYear = '';
		$prefix = config('database')['prefix'];
		if (isset($_POST['query']) || isset($_POST['export'])){
			$queryType = $_POST['queryType'];
			if ($queryType == 'month'){
				$startMonth = $this->request->post('startMonth');
				$endMonth = $this->request->post('endMonth');
				$count = current(Db::query("select COUNT(id) as c from {$prefix}delivery_order where date_format(from_unixtime(time),'%Y-%m')>='{$startMonth}' and date_format(from_unixtime(time),'%Y-%m')<='{$endMonth}' and status=3"));
				$yearAll[] = $startMonth.'-'.$endMonth;
				if (isset($_POST['export'])){
					$title = array('开始月份','结束月份','配送完成订单数（单）');
					$data[] = array('startMonth' => $startMonth,'endMonth' => $endMonth,'total' => $count['c']);
					$this->put_csv($data, $title, $startMonth.'-'.$endMonth.'订单月走势');
				}
			}elseif ($queryType == 'year'){
				$startYear = intval($this->request->post('startYear'));
				$endYear = intval($this->request->post('endYear'));
				$count = current(Db::query("select COUNT(id) as c from {$prefix}delivery_order where year(from_unixtime(time))>={$startYear} and year(from_unixtime(time))<={$endYear} and status=3"));
				$yearAll[] = $startYear.'-'.$endYear;
				if (isset($_POST['export'])){
					$title = array('开始年份','结束年份','配送完成订单数（单）');
					$data[] = array('startYear' => $startYear,'endYear' => $endYear,'total' => $count['c']);
					$this->put_csv($data, $title, $startYear.'-'.$endYear.'订单年走势');
				}
			}
			$totalData[] = $count['c'];
		}else{
			for ($i=1; $i <= 12; $i++){
				if ($i > 9){
					$pushTime = $year.'-'.$i;
					$yearAll[] = $pushTime;
				}else{
					$pushTime = $year.'-0'.$i;
					$yearAll[] = $pushTime;
				}
				// 唐峰康改 默认获取当前年份的  year(from_unixtime(time))='{$year}'
				$count = current(Db::query("select COUNT(id) as c from {$prefix}delivery_order where  year(from_unixtime(time))='{$year}' and month(from_unixtime(time))={$i} and status=3"));
				$total[] = array(
					'datetime' => $pushTime,
					'count' => $count['c'],
				);
				$totalData[] = $count['c'];
			}
		}
		$series = array(
			'series' => array(array(
				'name' => '配送完成订单数（单）',
				'data' => $totalData,
			)),
			'categories' => $yearAll,
		);
		$this->assign('startMonth',$startMonth);
		$this->assign('endMonth',$endMonth);
		$this->assign('startYear',$startYear);
		$this->assign('endYear',$endYear);
		$this->assign('series',json_encode($series));
		return $this->fetch();
	}
	
	public function water(){
		$lists = db('water w')->join('user u','w.uid=u.id','inner')->field('w.*,u.truename,u.mobile')->order('w.time desc')->paginate(config('PAGE_SIZE'));
		$this->assign('page',$lists->render());
		$this->assign('lists',$lists);
		return $this->fetch();
	}
		
}